package com.gradledemo.controller.admin;

/*
 * Copyright (c) 2010-2015 LiZaoNet Inc. (http://www.lizaonet.com).
 * license: http://www.lizaonet.com
 */

import com.gradledemo.dto.request.User;
import com.gradledemo.shiro.ShiroDbRealm;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Charles.Tan on 2015-01-29.
 */
@Controller
public class AdminLoginAction extends BaseAdminAction {
    private static final Logger log = LogManager.getLogger(AdminLoginAction.class);

    /**
     * 管理员登录方法
     *
     * @param user               登录账号
     * @param bindingResult      绑定值
     * @param redirectAttributes 重写向传来的值
     *
     * @return 返回访问地址
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(User user, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute(ShiroDbRealm.ROLE_KEY, ShiroDbRealm.ROLE_ADMIN);
        if (bindingResult.hasErrors()) {
            return "admin/login/login";
        }

        String userName = user.getUserName();

        UsernamePasswordToken token = new UsernamePasswordToken(userName,
                com.gradledemo.common.encode.MD5.getMD5ofStr(user.getPassw()));
        token.setRememberMe(true);
        try {
            subject.login(token);

            session.setAttribute(ShiroDbRealm.ADMIN_IS_LOGIN, true);
            session.setAttribute(ShiroDbRealm.SESSION_ADMIN_USER_NAME, userName);


            log.info("userName:" + userName + " login.");

            return "redirect:/admin/index.htm";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            redirectAttributes.addFlashAttribute("message", "账号名或密码错误");
            redirectAttributes.addFlashAttribute("style", "style='display:block;'");
            return "redirect:/admin/login.htm";
        }
    }

    /**
     * 登录的过滤方法，如果用户已经登录，既进入主页面，如果用户没有登录，则进行登录。
     *
     * @param request 请求 Request
     *
     * @return 返回页面
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String loginForm(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            if (null != session.getAttribute(ShiroDbRealm.ADMIN_IS_LOGIN) &&
                    Boolean.valueOf(String.valueOf(session.getAttribute(ShiroDbRealm.ADMIN_IS_LOGIN)))) {
                return "redirect:/admin/index.htm";
            }
        }
        return "admin/login/login";
    }

    /**
     * 登录出方法
     *
     * @param redirectAttributes 重定向参数
     * @return 显示视图
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout(RedirectAttributes redirectAttributes) {
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Session session = subject.getSession();
        session.setAttribute(ShiroDbRealm.ADMIN_IS_LOGIN, null);
        log.info("userName:" + session.getAttribute(ShiroDbRealm.SESSION_ADMIN_USER_NAME) + " logout.");
        session.setAttribute(ShiroDbRealm.SESSION_ADMIN_USER_NAME, null);
        redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return "redirect:/admin/login.htm";
    }
}
